package myLearnjdk.jdk.arithmetic.Spearman;

import java.math.BigDecimal;

/**
 * 斯皮尔曼等级相关性-Spearman Rank Correlation
 * @author yangcheng  
 * @date 2020年1月3日  
 * @version V1.0
 */
public class SpearmanRankCorrelation {
public static double correlation(int[] base, int[] other) {
		
		if (base.length != other.length) {
			System.err.println("The length of array base and other must be equal!");
			return 0.0;
		}
		if (base.length <= 1) {
			System.err.println("The length of both of the arrays must be equal!");
			System.exit(-1);
		}
		BigDecimal bg = new BigDecimal(1-(6.0*sumOfSquareDiff(base, other)/(power(base.length, 3)-base.length)));
		return bg.setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue();
	}
	
	private static double sumOfSquareDiff(int[] a, int[] b) {
		
		double sum = 0.0;
		for (int i = 0; i < a.length; i++) 
			sum += power((a[i]-b[i]), 2);
		return sum;
	}
	
	/*
	 * Method should do one thing 
	 * <<Clean code: A handbook of Agile software craftsmanship>>
	 */
	private static double power(double base, int exp) {
		
		if (base == 0)
			return 0.0;
		double result = 1.0;
		for (int i = 0; i < exp; i++)
			result *= base;
		return result;
	}
	
	
	
	public static void main(String[] args) {
		int[] base = {1, 2, 3, 4, 5};
		int[] other1 = {1, 2, 3, 4, 5};
		int[] other2 = FisherYatesShuffle.shuffle(base.clone());
		int[] other3 = {5, 4, 3, 2, 1};
		System.out.println(SpearmanRankCorrelation.correlation(base, other1));	
		System.out.println(SpearmanRankCorrelation.correlation(base, other2));
		System.out.println(SpearmanRankCorrelation.correlation(base, other3));
	}

}
